package com.autoscript.ui.helper;

import java.util.Iterator;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.autoscript.ui.model.xml.IXmlAttribute;
import com.autoscript.ui.model.xml.IXmlNode;
import com.autoscript.ui.model.xml.XmlAttribute;
import com.autoscript.ui.model.xml.XmlNode;

public class XMLHelper {

	/**
	 * 把XML字符串转换成模型
	 * 
	 * @param xmlStr
	 * @return IXmlNode
	 * @throws DocumentException 
	 */
	public static IXmlNode xml2Model(String xmlStr) throws DocumentException {
		IXmlNode rootNode = new XmlNode();
		try {
			Document doc;
			doc = DocumentHelper.parseText(xmlStr);
			Element rootElement = doc.getRootElement();
			xml2Model(rootElement, rootNode);

			return rootNode;

		} catch (DocumentException e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 递归方法 获得节点的值，如果某节点下还有子节点，则些key对应的value也是一个map
	 * 
	 * @param element
	 * @param map 
	 */
	private static void xml2Model(Element element, IXmlNode node) {
		Iterator i = element.elementIterator();
		String key = element.getName();
		Iterator i2 = element.attributeIterator();
		if (!i.hasNext()) {
			String value = element.getTextTrim();
			node.setName(key);
			node.setValue(value);
		} else {
			node.setName(key);
			//node.value没意义，不用设置
			while (i.hasNext()) {
				IXmlNode childNode = new XmlNode();
				node.getChildNodes().add(childNode);
				Element childElement = (Element) i.next();
				xml2Model(childElement, childNode);
			}
		}
		if (i2.hasNext()) {
			while (i2.hasNext()) {
				IXmlAttribute xmlAttr = new XmlAttribute();
				Attribute attribute = (Attribute) i2.next();
				String attrName = attribute.getName();
				String attrValue = attribute.getValue();
				xmlAttr.setName(attrName);
				xmlAttr.setValue(attrValue);
				node.getAttributes().add(xmlAttr);
			}
		}
	}
	/**
	 * 将xml特殊字符转义
	 * @param val 原始文本
	 * @return 返回转义后文本 
	 */
	public static String transferred(String val){
		if(val!=null){
			StringBuffer buff = new StringBuffer();
			buff.append(val);
			//'<' 转义
			buff = StringHelper.replaceAll(buff,"<", "&lt;");
			//'>' 转义
			buff = StringHelper.replaceAll(buff,">", "&gt;");
			//'&' 转义
			buff = StringHelper.replaceAll(buff,"&", "&amp;");
			//单引号 转义
			buff = StringHelper.replaceAll(buff,"'", "&apos;");
			//双引号 转义
			buff = StringHelper.replaceAll(buff,"\"", "&quot;");
			return buff.toString();
		}else{
			return null;
		}
	}
}
